<?php
include_once LIBRARIES_TOOLS_XTEMPLATE;
include_once LIBRARIES_ENTITIES_DATABASE;
include_once LIBRARIES_ENTITIES_VIDEOS;

class BlockVideoController {

    public function invoke() {

        // directory running file
        $dir = dirname(__FILE__);

        // get video list
        $videos = $this->getListVideo();

        // amount of video
        $amountVideo = count($videos);

        if ($amountVideo > 0) {

            // xtemplate file
            $xtemplate = new XTemplate($dir . '/views/video.html');

            // loop each video
            for ($i = 0; $i < $amountVideo; $i++) {
                
                $filePath = $videos[$i]->getFilePath();
                
                if ($videos[$i]->getFromYouTube() == 1) {
                    $filePath = substr($filePath, strpos($filePath, '?v=') + 3, strlen($filePath));
                }

                if ($i == 0) {
                    $xtemplate->assign("FIRST_FILE_PATH", $filePath);
                    $xtemplate->assign("FIRST_IMAGE", $videos[$i]->getImage());
                    $xtemplate->assign("FIRST_FROM_YOUTUBE", $videos[$i]->getFromYouTube());
                }

                $xtemplate->assign("IMAGE", $videos[$i]->getImage());
                $xtemplate->assign("FILE_PATH", $filePath);
                $xtemplate->assign("TITLE", $videos[$i]->getTitle());
                $xtemplate->assign("FROM_YOUTUBE", $videos[$i]->getFromYouTube());
                $xtemplate->parse("main.video_link");
            }
            $xtemplate->parse("main");
            $xtemplate->out("main");
        }
    }

    // get video list
    private function getListVideo() {
        $db = new Database();
        try {

            $video = new Videos();
            $videos = $video->getList($db);
            $db->submitChanges();
            return $videos;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}

?>
